package com.mtons.mblog.modules.rabbitmq;

import com.alibaba.fastjson.JSONObject;
import com.mtons.mblog.base.utils.ObjectConvertUtils;
import com.mtons.mblog.modules.service.MessageService;
import com.mtons.mblog.modules.vo.MessageVO;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @ClassName: FollowMqHandler
 * @Auther: Jerry
 * @Date: 2020/5/22 14:08
 * @Desctiption: TODO
 * @Version: 1.0
 */
@Component

public class FollowMqHandler {

    private Logger log = LoggerFactory.getLogger(FollowMqHandler.class);

    @Autowired
    private MessageService messageService;

    @RabbitListener(queues = RabbitConstant.FOLLOW_QUEUE)
    public void handler(Message message, Channel channel) throws IOException {
        FollowMqMessage followMqMessage = (FollowMqMessage) ObjectConvertUtils.ByteToObject(message.getBody());

        log.info("FollowMqHandler -------> mq 收到一条消息： {}", JSONObject.toJSONString(followMqMessage));
        MessageVO nt = new MessageVO();
        nt.setFromId(followMqMessage.getFromUserId());
        nt.setUserId(followMqMessage.getFollowId());
        nt.setEvent(followMqMessage.getEvent());
        messageService.send(nt);

        // 手动ack
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }
}
